ASP.NET OutputCache - Substitution

With ASP.NET version 1.0 and 1.1, which parts of a page will be cached, and more importantly, which parties will be generated for each request, no matter what. This meant that whenever you want a small part of the page to refresh each request, the output cache command could not be used. It has changed with ASP.NET 2.0, where we can use the <asp: Substitution> tag to create areas outside the cached content. Take a look at the following example:


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ OutputCache duration="120" varybyparam="None" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Caching</title>
</head>
<body>
    <form id="form1" runat="server">
        Cached datestamp:<br />
        <%= DateTime.Now.ToString() %><br /><br />
        Fresh datestamp:<br />
        <asp:Substitution runat="server" id="UnCachedArea" methodname="GetFreshDateTime" />
    </form>
</body>
</html> 

The Substitution tag is a feature called method name, in which the name of a method that the string should be returned to the output. Once the page is loaded, no matter whether it has returned from the cache or generated freshly, this method will be called, and the replacement control will be filled with returned string. Here is CodeBehind, where you will see our GetFreshDateTime method:


using System;
using System.Data;
using System.Web;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected static string GetFreshDateTime(HttpContext context)
    {
        return DateTime.Now.ToString();
    }
}

Since the GetFreshDateTime method should be called from the Substitution control, it needs to "look" in a certain way - it is to take HttpContext as a parameter, it is to return a string, and it becomes static is. Now, the HTTP contact allows you to access all kinds of information about the request to return the appropriate price etc. For now, we only return to the current date-time. Run the example, and see how the first datestamp is cached, while the second is reloaded each time. Its as simple as that!